Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

177
Visualizações
Returning a promise from JQuery "on ready" function

According to the JQuery docs, the "recommended" syntax for executing code when the DOM objects become safe to manipulate (a.k.a. "on ready") is this syntax:

$(function() {
  // Handler for .ready() called.
});

The JQuery documentation makes no mention of what JQuery does with the return value, if any, provided by the function. Which brings me to my question: I want to await a promise in my function. Is there any reason why I can't decorate the function with the required async keyword, like this:

$(async function() {
  await someFuncThatReturnsAPromise();
});

According to the excellent JavaScript.info tutorial on the subject, the await keyword causes the function to return a resolved promise object. If JQuery doesn't care about the function result, then the fact that the function returns a promise object should (hopefully) have no effect on the underlying "call the page ready handlers" JQuery behavior.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It doesn't really do anything with the value returned, even if it's a Promise - and, for that reason, is a problem, because if the Promise rejects, you'll get an unhandled rejection:

$(async function() {
  await Promise.reject();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

(Specifically, what happens with the callback is - it's added as a .then handler to the internal readyList, and although there's a .catch chained onto it, it'll just re-throw the value returned.)

var readyList = jQuery.Deferred();

jQuery.fn.ready = function (fn) {

    readyList
        .then(fn)

        // Wrap jQuery.readyException in a function so that the lookup
        // happens at the time of error handling instead of callback
        // registration.
        .catch(function (error) {
            jQuery.readyException(error);
        });

    return this;
};

If the async function never rejects, then

$(async function() {
  await someFuncThatReturnsAPromise();
});

is just fine.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda